package per.jdz.pc.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class C {
    public static void main(String[] args) {
        DataC data = new DataC(0);
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                data.printA();
            }
        }, "A").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                data.printB();
            }
        }, "B").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                data.printC();
            }
        }, "C").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                data.printD();
            }
        }, "D").start();
        System.out.println("main end");
    }
}

// 资源类
// 等待 业务 通知
class DataC {
    private int num;

    private final Lock lock = new ReentrantLock();
    // 同步监视器, 精确控制
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();
    private final Condition conditionD = lock.newCondition();

    public DataC(int num) {
        this.num = num;
    }

    public void printA() {
        lock.lock();
        try {
            while (num != 0) conditionA.await();
            num = 1;
            System.out.println(Thread.currentThread().getName() + "=>" + "A");
            conditionB.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void printB() {
        lock.lock();
        try {
            while (num != 1) conditionB.await();
            num = 2;
            System.out.println(Thread.currentThread().getName() + "=>" + "B");
            conditionC.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void printC() {
        lock.lock();
        try {
            while (num != 2) conditionC.await();
            num = 3;
            System.out.println(Thread.currentThread().getName() + "=>" + "C");
            conditionD.signalAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void printD() {
        lock.lock();
        try {
            while (num != 3) conditionD.await();
            num = 0;
            System.out.println(Thread.currentThread().getName() + "=>" + "D");
            conditionA.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
